<template>
  <div class>
    <el-breadcrumb>
      <el-breadcrumb-item>人事管理</el-breadcrumb-item>
      <el-breadcrumb-item>人员排班</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表 -->
    <el-card class="box-card">
      <div class="search">
        <el-button type="info" @click="lastweek">上一周</el-button>
        <el-button type="primary" @click="dialogVisible = true" class="addbtn">新增排班</el-button>
        <el-button type="info" @click="nextweek">下一周</el-button>
        <div>
          <span>{{nextMonday}}</span>
          <span>星期一</span>
          <span>~</span>
          <span>{{lastsunday}}</span>
          <span>星期天</span>
        </div>
        <el-form size="mini" label-width="80px">
          <el-row class="bg-row">
            <el-form-item label="科室类别">
              <el-radio-group v-model="form.configId" @change="change">
                <el-col
                  v-for="(item,index) in workers"
                  :key="index"
                  :md="6"
                  :xs="18"
                  :sm="6">
                  <el-radio :label="item.id">{{ item.name }}</el-radio>
                </el-col>
              </el-radio-group>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <!-- 信息 -->
      <el-table :data="tableData" :span-method="objectSpanMethod" stripe border @selection-change="handleSelectionChange">
        <el-table-column label="科室类别" prop="configName"></el-table-column>
        <el-table-column label="门诊医生" prop="doctorName"></el-table-column>
        <el-table-column label="时间段" prop="timeQuantumName"></el-table-column>
        <el-table-column :label="monday1" prop="mondayStatus" width="130"></el-table-column>
        <el-table-column :label="thursday1" prop="thursdayStatus" width="130"></el-table-column>
        <el-table-column :label="wednesday1" prop="wednesdayStatus" width="130"></el-table-column>
        <el-table-column :label="thuesday1" prop="thuesdayStatus" width="130"></el-table-column>
        <el-table-column :label="friday1" prop="fridayStatus" width="130"></el-table-column>
        <el-table-column :label="saturday1" prop="saturdayStatus" width="130"></el-table-column>
        <el-table-column :label="sunday1" prop="sundayStatus" width="130"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="removeUserById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination background layout="total, prev, pager, next,jumper" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" :total="total"></el-pagination>
    </el-card>
    <!-- 添加信息 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="55%" @close="dialogClosed">
      <el-form label-width="120px" :model="form" :rules="formRules" ref="formRef">
        <el-form-item label="排班起始日期" prop="schedulingDay">
          <el-date-picker v-model="this.dateFormat2" value-format="yyyy-MM-dd 00:00:00" type="date" editable disabled></el-date-picker>
        </el-form-item>
        <el-form-item label="排班结束日期">
          <el-date-picker v-model="this.dateFormat8" value-format="yyyy-MM-dd 00:00:00" type="date" editable disabled></el-date-picker>
        </el-form-item>
        <el-form-item label="科室类别" prop="staffId">
          <el-select v-model="form.configId" placeholder="科室类别">
            <el-option v-for="item in workers" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
            <el-form-item label="门诊医生工号">
              <!-- <el-select v-model="dataForm.userId" placeholder="请选择" @change="userNameChange($event)">
                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select> -->
              <el-input v-model="form.doctorId" placeholder="请输入工号" @change="workNumberChange(form.doctorId)"></el-input>
            </el-form-item>
            <el-form-item label="门诊医生名称">
              <el-input v-model="form.doctorName" disabled></el-input>
            </el-form-item>
         <!-- <span slot="footer" class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="shopSendOrder" :loading="ischeck" v-prevent-re-click>确 定</el-button>
        </span>-->
        <!--<el-form-item label="门诊医生" prop="staffId">
        <el-input v-model="form.doctorId" placehold="门诊医生"></el-input>
      </el-form-item>-->
        <el-form-item label="时间段" prop="staffId">
          <el-select v-model="form.timeQuantum" placeholder="时间段">
            <el-option :value="1" label="上午"></el-option>
            <el-option :value="2" label="下午"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="星期一" prop="mondayStatus">
          <el-input v-model="form.mondayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期二" prop="thursdayStatus">
          <el-input v-model="form.thursdayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期三" prop="wednesdayStatus">
          <el-input v-model="form.wednesdayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期四" prop="thuesdayStatus">
          <el-input v-model="form.thuesdayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期五" prop="fridayStatus">
          <el-input v-model="form.fridayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期六" prop="saturdayStatus">
          <el-input v-model="form.saturdayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
        <el-form-item label="星期日" prop="sundayStatus">
          <el-input v-model="form.sundayStatus" size="medium" placeholder="排班状态"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- end -->
  </div>
</template>

<script>
  import {
    delObj,
    addObj,
    putObj,
    fetchList
  } from '@/api/eims/doctor-rota'
  import {
    getRegisterConfigList
  } from '@/api/eims/register-config'
  import { getUserListNoRole, getUserInfo } from '@/api/admin/user.js'
  export default {
    data() {
      return {
        monday1: "",
        thursday1: "",
        wednesday1: "",
        thuesday1: "",
        friday1: "",
        saturday1: "",
        sunday1: "",
        base: "",
        monday: "",
        today: "",
        dateFormat2: "",
        dateFormat8: "",
        nextMonday: "",
        lastsunday: "",
        queryInfo: {
          query: "",
          pagenum: 1,
          pagesize: 10
        },
        role: false,
        homes: [],
        workers: [],
        total: 0,
        tableData: [],
        title: "新增",
        dialogVisible: false,
        form: {
          configId: "",
          doctorId: "",
          doctorName: "",
          timeQuantum: "",
          mondayStatus: "",
          thursdayStatus: "",
          wednesdayStatus: "",
          thuesdayStatus: "",
          fridayStatus: "",
          saturdayStatus: "",
          sundayStatus: "",
          beginTime: "",
          endTime: "",
          workNumber: "",
          userName: "",
        },
        formRules: {}
      };
    },
    components: {},
    created() {},
    watch: {},
    created() {
      this.getTableList();
      this.getWorkers();
      this.getTime();
    },
    methods: {
      //根据工号查询员工信息
      workNumberChange(data) {
          getUserInfo(data).then(result => {
              console.log(result.data.data.realName)
              if (result.data.data) {
                  this.form.doctorId = result.data.data.workNumber
                  this.form.doctorName = result.data.data.realName
              } else {
                  this.$message.warning("请输入正确的加工师工号");
              }
          })
      },
      lastweek() {
        this.getBeforNday(this.base, 7);
        // console.log(this.dateFormat2);
        this.getTableList();
      },
      nextweek() {
        this.getBeforNday(this.base, -7);
        // console.log(this.dateFormat2);
        this.getTableList();
      },
      getTime() {
        let myDate = new Date();
        let year = myDate.getFullYear();
        let month = myDate.getMonth() + 1;
        let date = myDate.getDate();
        let str = myDate.getDay();
        // console.log(str, 888);
        if (str == 1) {
          this.getBeforNday(myDate, 1);
        }
        if (str == 2) {
          this.getBeforNday(myDate, 2);
        }
        if (str == 3) {
          this.getBeforNday(myDate, 3);
        }
        if (str == 4) {
          this.getBeforNday(myDate, 4);
        }
        if (str == 5) {
          this.getBeforNday(myDate, 5);
        }
        if (str == 6) {
          this.getBeforNday(myDate, 6);
        }
        if (str == 0) {
          this.getBeforNday(myDate, 0);
        }
      },
      getBeforNday(date, n) {
        let todays = date.getTime();
        let today = new Date();
        this.today = today.setTime(todays);

        let yesterday_milliseconds = date.getTime() - n * 1000 * 60 * 60 * 24;
        let yesterday = new Date();

        yesterday.setTime(yesterday_milliseconds);

        let strYear = yesterday.getFullYear();
        let strDay = yesterday.getDate();
        let strMonth = yesterday.getMonth() + 1;
        let strdate = yesterday.getDay();

        if (strdate == 0) {}
        if (strMonth < 10) {
          strMonth = "0" + strMonth;
        }
        let datastr = strYear + "年" + strMonth + "月" + strDay + "日";
        let md = strMonth + "-" + strDay;
        this.sunday = md;
        this.lastsunday = datastr;
        this.dateFormat1 = strYear + "-" + strMonth + "-" + strDay;
        this.base = yesterday;
        this.getotherday(yesterday, -1);
        this.getotherday(yesterday, -2);
        this.getotherday(yesterday, -3);
        this.getotherday(yesterday, -4);
        this.getotherday(yesterday, -5);
        this.getotherday(yesterday, -6);
        this.getotherday(yesterday, -7);
      },
      getotherday(date, n) {
        let yesterday_milliseconds = date.getTime() - n * 1000 * 60 * 60 * 24;
        let yesterday = new Date();
        yesterday.setTime(yesterday_milliseconds);

        let strYear = yesterday.getFullYear();
        // console.log(yesterday);
        let strDay = yesterday.getDate();
        let strMonth = yesterday.getMonth() + 1;
        let strdate = yesterday.getDay();
        if (strMonth < 10) {
          strMonth = "0" + strMonth;
        }
        if (strDay < 10) {
          strDay = "0" + strDay;
        }
        if (n == -1) {
          this.monday = strMonth + "." + strDay;
          this.monday1 = "星期一(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.nextMonday = strYear + "年" + strMonth + "月" + strDay + "日";
          this.dateFormat2 =
            strYear + "-" + strMonth + "-" + strDay + " " + "00:00:00";
        }
        if (n == -2) {
          this.thursday = strMonth + "." + strDay;
          this.thursday1 = "星期二" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.dateFormat3 = strYear + "-" + strMonth + "-" + strDay;
        }
        if (n == -3) {
          this.wednesday = strMonth + "." + strDay;
          this.wednesday1 = "星期三" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.dateFormat4 = strYear + "-" + strMonth + "-" + strDay;
        }
        if (n == -4) {
          this.thuesday = strMonth + "." + strDay;
          this.thuesday1 = "星期四" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.dateFormat5 = strYear + "-" + strMonth + "-" + strDay;
        }
        if (n == -5) {
          this.friday = strMonth + "." + strDay;
          this.friday1 = "星期五" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.dateFormat6 = strYear + "-" + strMonth + "-" + strDay;
        }
        if (n == -6) {
          this.saturday = strMonth + "." + strDay;
          this.saturday1 = "星期六" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.dateFormat7 = strYear + "-" + strMonth + "-" + strDay;
        }
        if (n == -7) {
          this.sunday = strMonth + "." + strDay;
          this.sunday1 = "星期天" + "(" + strYear + " / " + strMonth + " / " + strDay + ")";
          this.lastsunday = strYear + "年" + strMonth + "月" + strDay + "日";
          this.dateFormat8 =
            strYear + "-" + strMonth + "-" + strDay + " " + "00:00:00";
        }
      },

      handleChange_1(data) {
        // console.log(data);
      },
      handleChange_2(data) {
        // console.log(data, 123);
      },
      dialogClosed() {
        this.form = {};
        this.title = "新增";
        this.dialogVisible = false;
      },
      // 合并表格
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          let sum = 1
          let data = this.tableData
          // 判断上一行数据是否跟本行相同
          // 跟本行相同，则本行被合并，本行跳过
          // 不相同，则向下循环查找相同的数据
          if(data[rowIndex - 1] && row.configId === data[rowIndex - 1]['configId']){
            return {
              rowspan: 0,
              colspan: 1
            }
          }else{
            if(rowIndex + 1 <= data.length){
              for(let i = rowIndex;i < data.length;i++){
                if(data[i + 1] && row.configId === data[i + 1]['configId']){
                  sum += 1
                }else{
                  break
                }
              }
            }
            return {
              rowspan: sum,
              colspan: 1
            }
          }
        }
        if (columnIndex === 1) {
          let sum = 1
          let data = this.tableData
          // 判断上一行数据是否跟本行相同
          // 跟本行相同，则本行被合并，本行跳过
          // 不相同，则向下循环查找相同的数据
          if(data[rowIndex - 1] && row.doctorId === data[rowIndex - 1]['doctorId']){
            return {
              rowspan: 0,
              colspan: 1
            }
          }else{
            if(rowIndex + 1 <= data.length){
              for(let i = rowIndex;i < data.length;i++){
                if(data[i + 1] && row.doctorId === data[i + 1]['doctorId']){
                  sum += 1
                }else{
                  break
                }
              }
            }
            return {
              rowspan: sum,
              colspan: 1
            }
          }
        }
      },
      //获取workers
      async getWorkers() {
        getRegisterConfigList().then(result => {
          let dataList = result.data.data
          let options = []
          dataList.forEach(item => {
            options.push({
              value: item.id,
              name: item.name
            })
          })
          // console.log(dataList)
          this.workers = dataList
        })
      },
      getTableList() {
        this.form.beginTime = this.dateFormat2;
        this.form.endTime = this.dateFormat8;
        console.log(this.form)
        fetchList(Object.assign({
          current: this.pageIndex,
          size: this.pageSize
        }, this.form)).then(response => {
          this.tableData = response.data.data.records;
          console.log(this.tableData)
        })
      },
      async removeUserById(id) {
        // 弹框询问用户是否删除数据
        const confirmResult = await this.$confirm(
          "此操作将永久删除该数据, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).catch(err => err);

        // 如果用户确认删除，则返回值为字符串 confirm
        // 如果用户取消了删除，则返回值为字符串 cancel
        // console.log(confirmResult)
        if (confirmResult !== "confirm") {
          return this.$message.info("已取消删除");
        }
        delObj(id).then(res => {
          this.getTableList();
          this.$message.success("删除数据成功！");
        });
        this.dialogVisible = false;
        if (res.msg !== "success") {
          return this.$message.error("删除数据失败");
        }
        this.getTableList();
        this.$message.success("删除数据成功！");
      },
      //添加or修改
      async showEditDialog(row) {
        this.form = row;
        this.title = "修改排班";
        this.dialogVisible = true;
      },
      change() {
        this.getTableList();
      },
      handleSubmit() {
        if (this.title == "修改排班") {
          putObj(this.form).then(res => {
            this.getTableList();
            this.$message.success("修改数据成功！");
          });
          this.dialogVisible = false;
        } else {
          let a = sessionStorage.getItem("elderlyHomeId");
          this.form.elderlyHomeId = a;
          this.form.schedulingDay = this.dateFormat2;
          this.form.beginTime = this.dateFormat2;
          this.form.endTime = this.dateFormat8;
          addObj(this.form).then(res => {
            this.getTableList();
            this.$message.success("添加数据成功！");
          });
          this.dialogVisible = false;
        }
      },
      handleSelectionChange(val) {
        this.checkedList = val;
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage;
        this.getTableList();
      }
    }
  };
</script>
<style lang="less" scoped>
</style>
